package com.example.smslistener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsService extends Service{

	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		receiveMessage(intent);
		
		onDestroy();
	}

	public class LocalBinder extends Binder{
		SmsService getService(){
			return SmsService.this;
		}
	}
	
	private void receiveMessage(Intent service){
		Intent intent = (Intent)service.getExtras().get("intent");
		if(intent.getAction().equals(SMS_RECEIVED)){
			Bundle bundle = intent.getExtras();
			Object[] pdus = (Object[]) bundle.get("pdus");
			SmsMessage[] messages = new SmsMessage[pdus.length];
			for(int i =0;i<pdus.length;i++){
				messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			}
			
			StringBuffer body = new StringBuffer();
			String from = messages[0].getOriginatingAddress();
			Date date = new Date(messages[0].getTimestampMillis());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			
			for(SmsMessage msg : messages){
				body.append(msg.getMessageBody());
			}
			String info = "From:" + from + "\nDate:" + sdf.format(date) + "\nBody:" + body.toString() + "\n\n";
			save(info);
		}
	}
	
	private void save(String s){
		FileOutputStream fos = null;
		try {
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				String path = Environment.getExternalStorageDirectory().getPath() + "/smsListener/incoming";
				File dir = new File(path);
				if(!dir.exists()){
					dir.mkdirs();
				}
				fos = new FileOutputStream(new File(dir,"messages.txt"),true);
				fos.write(s.getBytes());
				fos.flush();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
